package youleche.com.sql.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import youleche.com.sql.servlet.common.SqlGenerateFactory;
import youleche.com.sql.servlet.common.SuperHttpServlet;

/**
 * 文件上传
 */
public class SFileUploadServlet extends SuperHttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SFileUploadServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("rawtypes")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				;
				FileItem item = (FileItem) it.next();
				if (item.isFormField()) {
					System.out.println("表单参数名:" + item.getFieldName()
							+ "，表单参数值:" + item.getString("UTF-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						InputStream uploadedStream = item.getInputStream();  
						BufferedReader reader = new BufferedReader(new InputStreamReader(uploadedStream));
				        StringBuilder builder = new StringBuilder();

				        String line = null;
				        try {
				            while ((line = reader.readLine()) != null) {
				                builder.append(line);
				                builder.append("\n");
				            }
				        } catch (IOException e) {
				            e.printStackTrace();
				        } finally {
				            try {
				            	uploadedStream.close();
				            } catch (IOException e) {
				                e.printStackTrace();
				            }
				        }
				        
				        SqlGenerateFactory.parseCreateTableSql(builder.toString());
					} else {
						request.setAttribute("upload.message", "没有选择上传文件！");
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
